﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Obligatorio2013.Clases;
using Obligatorio2013.Persistencia;
using Obligatorio2013.Persistencia.Daos;
using Obligatorio2013.Logging;

namespace Obligatorio2013.Modelo
{
    public class CategoryController
    {

        #region Singleton
        private readonly static CategoryController _instance = new CategoryController();
        public static CategoryController Instance { get { return _instance; } }
        private CategoryController()
        {
            try
            {
                catDao = new CategoryDAO();
                this.categories = catDao.getAll().Cast<Category>().ToList();
                Log.Instance.Info("Categorias cargadas : " + this.categories.Count);

            }
            catch (Exception ex)
            { 
                Log.Instance.Error("Error cargando lista : " + ex.StackTrace);
            }

        }
        #endregion

        private CategoryDAO catDao;
        private List<Category> categories = null;

        public List<Category> CategoryList { get { return this.categories; } }


        public bool validateName(String name)
        {
            return !string.IsNullOrEmpty(name);
        }

        public void saveCategory(Category cat)
        {
            if (categories == null) { 
                categories = new List<Category>(); 
            }
            try
            {
                if (findCategoryById(cat.Name) == null)
                {
                    if (catDao.Save(cat))
                    {
                        categories.Add(cat);
                        Log.Instance.Info(cat.ToString() + " saved.");
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Instance.Error("Error salvando la categoria:", ex.StackTrace);
            }

        }

        public Category findCategoryById(string name)
        {
            Category cat = null;

            if (this.categories != null)
            {
                foreach (var category in this.categories)
                {
                    if (category.Name == name)
                    {
                        //name.Equals(name);
                        cat = category;
                        return cat;
                    }
                }
            }

            return cat;
        }

    }
}